package stattracker;

import java.util.ArrayList;
import java.util.Collection;
import java.util.TreeMap;

public class Halo3Team implements java.io.Serializable, Comparable<Halo3Team>
{
	private static final long serialVersionUID = 1L;
	private ArrayList<Halo3TeamMember> team;
	private String name;
	
	public Halo3Team(String name, ArrayList<Halo3TeamMember> members)
	{
		this.name = name;
		if(members.size() > 1 && members.size() <= 4)
			team = members;
		else
			new ErrorMessage("Can't have a one man team.");
	}
	
	public void update(BaseSystem sys)
	{
		findCommonGames(sys);
		updateAllStats();
	}
	
	public int getTeamGamesPlayed()
	{
		return team.get(0).getTeamGames().size();
	}
	
	public double winRatio()
	{
		int maxWins = 0;
		for(Halo3TeamMember m : team)
		{
			if(m.getTeamWins() > maxWins)
				maxWins = m.getTeamWins();
		}
		return ((double)maxWins) / team.get(0).getTeamGames().size();
	}
	
	public String getName()
	{
		return name;
	}
	
	public ArrayList<Halo3TeamMember> getTeam()
	{
		return team;
	}
	
	private void findCommonGames(BaseSystem sys)
	{
		ArrayList<TreeMap<Long, Halo3GameData>> allGames = new ArrayList<TreeMap<Long, Halo3GameData>>();
		for(Halo3TeamMember name : team)
		{
			allGames.add(sys.loadHalo3Data(name.getName(), false).getGames());
		}
		
		TreeMap<Long, Halo3GameData> captainGames = allGames.get(0);
		Collection<Halo3GameData> c = captainGames.values();
		ArrayList<Halo3GameData> baseGames = new ArrayList<Halo3GameData>(c);
		
		for(Halo3GameData g : baseGames)
		{
			boolean allPlayed = true;
			boolean teamGame = true;
			for(int i = 1; i < allGames.size(); i++)
			{
				if(g.getDetail().getColor().equals("FFA"))
					teamGame = false;
				if(!allGames.get(i).containsKey(g.getID()))
					allPlayed = false;
				else
				{
					if(!allGames.get(i).get(g.getID()).getDetail().getColor().equals(g.getDetail().getColor()))
						teamGame = false;
				}
			}
			
			if(allPlayed)
			{
				if(!team.get(0).getGamesPlayed().containsKey(g.getID()))
				{
					for(int i = 0; i < team.size(); i++)
					{
						team.get(i).addGame(allGames.get(i).get(g.getID()), teamGame);
					}
				}
			}
		}
	}
	
	private void updateAllStats()
	{
		for(Halo3TeamMember m : team)
			m.compileStats();
	}

	public int compareTo(Halo3Team other)
	{
		return name.toLowerCase().compareTo(other.getName().toLowerCase());
	}
	
}
